import requests, json
import serial
import time
from datetime import datetime
from datetime import timedelta


def rebbox(box, old_size, new_size):
    xmin, ymin, xmax, ymax = box

    xmin = max(int(round(xmin / old_size[0] * new_size[0])), 0)
    ymin = max(int(round(ymin / old_size[1] * new_size[1])), 0)
    xmax = min(int(round(xmax / old_size[0] * new_size[0])), new_size[0])
    ymax = min(int(round(ymax / old_size[1] * new_size[1])), new_size[1])
    return xmin, ymin, xmax, ymax


def postApi(url, data):
    data = json.dumps(data)

    r = requests.post(url, data, auth=('user', '*****'))

    print(r.json)


def utcToBj(ucttime):
    date = time.strftime("%Y%m%d", time.localtime())
    if len(ucttime) != 6:
        ctime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    else:
        uTime = f"{date}{ucttime}"
        atime = datetime.strptime(str(uTime), "%Y%m%d%H%M%S") + timedelta(hours=8)
        ctime = f"{time.strftime('%Y-%m-%d', time.localtime())} {atime.strftime('%H:%M:%S')}"
    return ctime


def get_gps_data(waittime=0):
    data = ''
    try:
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        ser.reset_input_buffer()
        cnt = 0
        while True:
            data = ser.readline()
            data = data.decode('GBK')
            if 'GNGGA' in data:
                # print(data)
                break
            if waittime:
                time.sleep(waittime)
            cnt += 1
            if cnt % 10 == 0:
                print('gps error，请检查GPS设备，并重启程序')
                break
    except:
        print('usb error,请检查USB插线，并重启程序')

    return data
